package com.newpage.module_gather.fragment;

import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.newpage.module_gather.R;
import com.newpage.module_gather.R2;
import com.newpage.module_gather.contract.QuestionRevisionCon;
import com.newpage.module_gather.presenter.QuestionRevisionPre;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.adapter.RecycleHolder;
import com.wetao.lib_common.adapter.RecyclerAdapter;
import com.wetao.lib_common.base.BaseLazyFragment;
import com.wetao.lib_common.bean.TabEntity;
import com.wetao.lib_common.bean.response.RevisionExamListInfo;
import com.wetao.lib_common.bean.response.SubjectInfo;
import com.wetao.lib_common.utils.BaseEvent;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.view.OnMultiClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * author: zhouyh
 * created on: 2021/6/17 10:19 上午
 * description:错题订正页面
 */
public class QuestionRevisionFragment extends BaseLazyFragment<QuestionRevisionCon.View, QuestionRevisionPre> implements QuestionRevisionCon.View {



    @BindView(R2.id.srl_question_revision)
    SmartRefreshLayout srl;
    @BindView(R2.id.lrv_question_revision)
    LRecyclerView lrv;

    @BindView(R2.id.rl_revision_noData)
    RelativeLayout rl_no_data;
    @BindView(R2.id.tl_subject)
    CommonTabLayout ctl_subject;//学科

    private LRecyclerViewAdapter lrvAdapter;
    private RecyclerAdapter<RevisionExamListInfo.DataBean.RecordsBean> examAdapter;
    private List<RevisionExamListInfo.DataBean.RecordsBean> examData = new ArrayList<>();




    private ArrayList<CustomTabEntity> mSubEntities = new ArrayList<>();
    private List<SubjectInfo.SubjectBean> subjectBeans = new ArrayList<>();


    private String subjectInfo;
    private volatile int subjectId;
    int current = 1;
    int pages = 1;
    int total = 1;
    int PAGESIZE = 10;
    int PAGE = 1;

    @Override
    public int getLayoutId() {
        return R.layout.gather_revision_fragment;
    }

    @Override
    public QuestionRevisionPre createPresenter() {
        return new QuestionRevisionPre(getActivity());
    }

    @Override
    public QuestionRevisionCon.View createView() {
        return this;
    }

    @Override
    public void init(View rootView) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        initAdapter();
        initRefresh();
        getSubjectReq();
    }


    private void initData() {

        if (subjectBeans != null && subjectBeans.size() > 0) {
            for (int i = 0; i < subjectBeans.size(); i++) {
                mSubEntities.add(new TabEntity(subjectBeans.get(i).getName(), 0, 0));
            }
            subjectId = subjectBeans.get(0).getId();
            ctl_subject.setTabData(mSubEntities);

            ctl_subject.setOnTabSelectListener(new OnTabSelectListener() {
                @Override
                public void onTabSelect(int position) {
                    subjectId = subjectBeans.get(position).getId();
                    getRevisionExamListReq(subjectId, current = PAGE);
                }

                @Override
                public void onTabReselect(int position) {

                }
            });
        }


    }


    @Override
    public void onResume() {
        super.onResume();
        getRevisionExamListReq(subjectId, current);
    }


    /**
     * 获取错题斩模块学科数据
     */
    private void getSubjectReq() {
        getPresenter().querySubjectBySectionId(ComUtil.getHashmapByStr(new String[]{}, new String[]{}), false, false);
    }
    /**
     * 请求数据
     */
    private void getRevisionExamListReq(Integer subjectId, Integer curPage) {
        getPresenter().getStudentRevisionExamList(ComUtil.getHashmapByStr(new String[]{"subjectId", "pageNo", "pageSize"},
                new String[]{String.valueOf(subjectId), String.valueOf(curPage), String.valueOf(PAGESIZE)}), false, false);
    }

    private void initRefresh() {

        srl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                getRevisionExamListReq(subjectId, current = PAGE);
            }

            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (current < pages) {
                    getRevisionExamListReq(subjectId, ++current);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });

        srl.setRefreshHeader(new ClassicsHeader(getActivity()));
        srl.setRefreshFooter(new ClassicsFooter(getActivity()));
    }


    /**
     * 初始化列表
     */
    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        lrv.setLayoutManager(linearLayoutManager);
        lrv.setNestedScrollingEnabled(false);
        lrv.setOverScrollMode(View.OVER_SCROLL_NEVER);
        examAdapter = new RecyclerAdapter<RevisionExamListInfo.DataBean.RecordsBean>(getActivity(), examData, R.layout.gather_revision_exam_item) {

            @Override
            public void convert(RecycleHolder holder, RevisionExamListInfo.DataBean.RecordsBean data, int position) {
                holder.setText(R.id.tv_gather_exam_title, StringUtil.replaceAmp(data.getExamName()));
                holder.setText(R.id.tv_gather_exam_time, String.format("完成时间: %s", data.getCreateTime()));
                holder.setText(R.id.tv_gather_revision_wrong_no, String.format("错题: %s", data.getWrongQuestionCount()));
                holder.setText(R.id.tv_gather_revision_no, String.format("订正: %s", data.getRevisionQuestionCount()));
                holder.setText(R.id.tv_gather_exam_state, String.format("状态: %s", getState(data.getIsRevision())));
                holder.itemView.setOnClickListener(new OnMultiClickListener() {
                    @Override
                    public void onMultiClick(View v) {
                        if (!ComUtil.isNetworkConnected()){
                            ToastUtil.initToast("网络已断开，请先检查网络");
                            return;
                        }
                        ARouter.getInstance().build(ConstantArouter.PATH_GATHER_REVISIONDETAILAILACTIVITY)
                                .withInt("studentExamId", data.getStudentExamId())
                                .withInt("examId", data.getExamId())
                                .withString("examName", data.getExamName())
                                .withInt("isRevision", data.getIsRevision())  //订正状态
                                .navigation();
                    }
                });
            }
        };
        lrvAdapter = new LRecyclerViewAdapter(examAdapter);
        lrv.setEmptyView(rl_no_data);
        lrv.setAdapter(lrvAdapter);
    }


    /**
     * 状态
     *
     * @param state
     * @return
     */
    private String getState(Integer state) {
        String result = null;
        switch (state) {
            case 0:
                result = "待订正";
                break;
            case 1:
                result = "已订正";
                break;
            case 2:
                result = "订正中";
                break;

        }
        return result;
    }


    private void finishRefresh() {
        if (current == 1) {
            resetNoMoreData();
            examData.clear();
        }
        hideRefresh();
    }

    private void hideRefresh(){
        if (srl != null) {
            srl.finishRefresh();
            srl.finishLoadMore();
        }
    }

    public void resetNoMoreData() {
        if (srl != null) {
            srl.resetNoMoreData();//去除没有更多数据状态
        }
    }


    @Override
    public void getStudentRevisionExamListResult(RevisionExamListInfo resp) {
        finishRefresh();
        if (resp.getData() != null && resp.getData().getRecords().size() > 0) {
            pages = resp.getData().getPages();
            PAGESIZE = resp.getData().getSize();
            total = resp.getData().getTotal();
            examData.addAll(resp.getData().getRecords());
            lrv.setEmptyView(rl_no_data);
        }
        lrvAdapter.notifyDataSetChanged();
        showEmpty();
    }

    private void showEmpty() {
        if (examData.size() > 0) {
            rl_no_data.setVisibility(View.GONE);
            srl.setVisibility(View.VISIBLE);
        } else {
            rl_no_data.setVisibility(View.VISIBLE);
            srl.setVisibility(View.GONE);
        }
    }

    @Override
    public void getStudentRevisionExamListFail() {
        hideRefresh();
    }

    @Override
    public void querySubjectBySectionIdResult(SubjectInfo resp) {
        if (resp.getData() != null && resp.getData().size() > 0) {
            subjectBeans.clear();
            subjectBeans.addAll(resp.getData());
            initData();
            getRevisionExamListReq(subjectId, current);
        }
    }

    @Override
    public void querySubjectBySectionIdFail() {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventReceived(BaseEvent event) {
        if (event.getCode() == Constants.ConstData.QUERY_EXAM_BY_SUBJECT) {
            subjectId = event.getId();
            getRevisionExamListReq(subjectId, current = PAGE);
        }
    }
}
